import axios from 'axios'
import store from '@/store'
import router from '@/router'
import * as constant from '@/config/constant'
import {Message} from 'element-ui'
import _ from 'lodash'

const showErrMsg = _.debounce(function (msg) {
  Message.error(msg)
}, 1000)

const service = axios.create({
  baseURL: constant.BASE_URL,
  timeout: 60000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.getters['user/token']
    if (token) {
      config.headers.Authorization = 'JWT ' + store.getters['user/token']
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response.status === 401) {
      store.commit('user/SET_LOGOUT')
      router.push({name: 'login'})

      showErrMsg.warning('登陆已失效')

      return Promise.reject(error)
    }

    return Promise.reject(error)
  }
)

export default service
